/**
 * dashboard 页面
 */

import styled from "@emotion/styled";
import ItemCardView from "./item-card"
import { Avatar, Card, Spin } from "antd";
import {
  BorderOuterOutlined,
  UserOutlined,
  FileDoneOutlined,
  RubyOutlined
} from '@ant-design/icons';
import { IPieVO, useGetCardPieVOByBeefSource, useGetCardPieVOByKeyPersonnel, useGetCardPieVOByRiskLevel, useGetSysHomeCardValue, useGetTaskStatistic ,useExportAllOfJoin } from "../../../service/statistic-service";
import { useEffect } from "react";
import { Chart, render } from "@antv/g2";
import { CardHader } from "../../../csscomponents/base";
import {useDowLoad} from "../../../utils/download";

const DashboardPage = () => {

  const { data: dataSource } = useGetSysHomeCardValue();
  
  const { data: dataSourceType } = useGetTaskStatistic();

  const doloadFile = useDowLoad()
  useEffect(() => { 
    const e = document.createEvent('Event')
    e.initEvent('resize', true, true)
    window.dispatchEvent(e)
  })
  useEffect(() => {
    const chart = new Chart({ container: 'container', autoFit: true });
    chart
      .interval()
      .data(dataSourceType)
      .encode('x', 'name')
      .encode('y', 'value')
      .encode('color', 'name')
    chart.render();
  }, [dataSourceType])

  //渲染纠纷来源统计
  const { data: dataSourcePieVOByBeefSource } = useGetCardPieVOByBeefSource();
  useEffect(() => {
    if (dataSourcePieVOByBeefSource) {
      renderBeefSource(dataSourcePieVOByBeefSource)
    }
  }, [dataSourcePieVOByBeefSource])
  //渲染风险等级统计
  const { data: dataSourcePieVOByRiskLevel } = useGetCardPieVOByRiskLevel();
  useEffect(() => {
    if (dataSourcePieVOByRiskLevel) {
      renderRiskLevel(dataSourcePieVOByRiskLevel)
    }
  }, [dataSourcePieVOByRiskLevel])


  const renderBeefSource = (data: IPieVO[]) => {
    const chart = new Chart({
      container: 'beef-source',
      autoFit: true,
    });
    chart.coordinate({ type: 'theta', outerRadius: 0.8, innerRadius: 0.5 });
    chart
      .interval()
      .data(data)
      .transform({ type: 'stackY' })
      .encode('y', 'percent')
      .encode('color', 'item')
      .label({
        text: (data: IPieVO) => `${data.count}`,
        fontWeight: 'bold',
        offset: 14,
      })
      .legend('color', { position: 'bottom', layout: { justifyContent: 'center' } })
      .label({
        position: 'outside',
        text: (data: IPieVO) => `${data.item}: ${(data.percent * 100).toFixed(2)}%`,
      })
      .tooltip((data) => ({
        name: data.item,
        value: `${(data.percent * 100).toFixed(2)}%`,
      }));
    chart.render();
  }

  const renderRiskLevel = (data: IPieVO[]) => {
    const chart = new Chart({
      container: 'risk-level',
      autoFit: true,
    });
    chart.coordinate({ type: 'theta', outerRadius: 0.8 });
    chart
      .interval()
      .data(data)
      .transform({ type: 'stackY' })
      .label({
        text: (data: IPieVO) => `${data.count}`,
        fontWeight: 'bold',
        offset: 14,
      })
      .encode('y', 'percent')
      .encode('color', 'item')
      .legend('color', { position: 'bottom', layout: { justifyContent: 'center' } })
      .label({
        position: 'outside',
        text: (data: IPieVO) => `${data.item}: ${(data.percent * 100).toFixed(2)}%`,
      })
      .tooltip((data) => ({
        name: data.item,
        value: `${(data.percent * 100).toFixed(2)}%`,
      }));
    chart.render();
  }


  //渲染重点人员统计
  const { data: dataSourcePieVOByKeyPersonnel } = useGetCardPieVOByKeyPersonnel();
  useEffect(() => {
    if (dataSourcePieVOByKeyPersonnel) {
      renderKeyPersonnel(dataSourcePieVOByKeyPersonnel)
    }
  }, [dataSourcePieVOByKeyPersonnel])

  const renderKeyPersonnel = (data: IPieVO[]) => {
    const chart = new Chart({
      container: 'major',
      autoFit: true,
    });
    chart.coordinate({ type: 'theta', outerRadius: 0.8 });
    chart
      .interval()
      .data(data)
      .transform({ type: 'stackY' })
      .encode('y', 'percent')
      .scale('color', {
        range: ['#e8c1a0', '#f47560', '#f1e15b', '#e8a838', '#61cdbb'],
      })
      .encode('color', 'item')
      .label({
        text: (data: IPieVO) => `${data.count}`,
        fontWeight: 'bold',
        offset: 14,
      })
      .legend('color', { position: 'bottom', layout: { justifyContent: 'center' } })
      .label({
        position: 'outside',
        text: (data: IPieVO) => `${data.item}: ${(data.percent * 100).toFixed(2)}%`,
      })
      .tooltip((data) => ({
        name: data.item,
        value: `${(data.percent * 100).toFixed(2)}%`,
      }));
    chart.render();
  }

  const exportData =async ()=>{
    try {
      doloadFile('/export/exportTaskStatistic',{}).then((res:any)=>{
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(res);
      a.href = url;
      a.download = "矛盾纠纷类型统计.xls"; // 设置下载文件的名称
      a.click();
      })

    } catch (error) {
      console.error("下载文件时出现错误：", error);
    }
    
  }
  const exportDataAll =async ()=>{
    try {
      doloadFile('/export/exportAllOfJoin',{}).then((res:any)=>{
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(res);
      a.href = url;
      a.download = "全部数据统计.xls"; // 设置下载文件的名称
      a.click();
      })

    } catch (error) {
      console.error("下载文件时出现错误：", error);
    }
    
  }
  return <DashboardPageView>
    <CardHader ><div>数据统计</div> <div onClick={exportDataAll} style={{cursor:'pointer'}}>导出数据</div></CardHader>
    <PageHeader>
      <ItemCardView value={dataSource && dataSource[0] ? dataSource[0].count : 0} title={"总数"} icon={<Avatar icon={<BorderOuterOutlined />} style={{ backgroundColor: 'rgb(230, 247, 255)', color: 'rgb(64, 169, 255)' }} />} />
      <ItemCardView value={dataSource && dataSource[1] ? dataSource[1].count : 0} title={"调解完成数"} icon={<Avatar icon={<FileDoneOutlined />} style={{ backgroundColor: 'rgb(210, 227, 125)', color: 'rgb(255, 255, 255)' }} />} />
      <ItemCardView value={dataSource && dataSource[2]  ? (dataSource[2].percent * 100).toFixed(2)+ '%' : '0.0%'} title={"调解完成率"} icon={<Avatar icon={<RubyOutlined />} style={{ backgroundColor: 'rgb(20, 27, 55)', color: 'rgb(255, 255, 255)' }} />} />
      {/* <ItemCardView value={dataSource?.userCount || 0} title={"用户数量"} icon={<Avatar icon={<UserOutlined />} style={{ backgroundColor: 'rgb(130, 147, 225)', color: 'rgb(255, 255, 255)' }} />} /> */}
    </PageHeader>
    <div style={{ marginTop: ' 1rem' }}>
      <CardHader ><div>矛盾纠纷类型统计</div> <div onClick={exportData} style={{cursor:'pointer'}}>导出数据</div></CardHader>
      
      <PageCenter >
        <div id="container" className="left-center"></div>
      </PageCenter>
    </div>
    <div className={'footer'}>
      <div style={{ backgroundColor: '#fff' }}>
        <CardHader >矛盾纠纷来源数量统计</CardHader>
        <div id="beef-source" style={{ height: 'calc(100% - 3rem)' }}></div>
      </div>
      <div style={{ backgroundColor: '#fff' }}>
        <CardHader >风险等级数据统计</CardHader>
        <div id="risk-level" style={{ height: 'calc(100% - 3rem)' }}></div>
      </div>
      <div style={{ backgroundColor: '#fff' }}>
        <CardHader >重点统计</CardHader>
        <div id="major" style={{ height: 'calc(100% - 3rem)' }}></div>
      </div>
    </div>
  </DashboardPageView>;
};

export default DashboardPage;

const DashboardPageView = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;

  .footer {
    flex: 1;
    margin-bottom: 6rem;
    padding-bottom: 3rem;
    display: flex;
    gap: 1rem;
   >div{
    flex: 1;
    height: 100%;
   }
}

`
export const PageHeader = styled.div` 
  height: 10rem;
  margin-bottom: 12px;
  display: flex;
  gap: 1rem;
  >div{
    flex: 1;
  }
  
`
const PageCenter = styled.div`
  height: 25rem;
  margin-bottom: 12px;
  flex-direction: row;
  gap: 1rem;
  display: flex;
 .left-center {
    flex: 3;
    background-color:#fff;
  }

  .right-center {
    flex: 1;
    background-color:#fff;
  }
`





















